<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>走口子</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .main {
            position: relative;
            width: 400px;
            height: 400px;
            border: 1px solid lawngreen;
        }

        .main .box {
            position: absolute;
            width: 20px;
            height: 20px;
            background: red;
            top: 0;
            left: 0;
        }
    </style>

</head>

<body>
    <div class="main">
        <div class="box"></div>
    </div>
    <button>开始</button>
    <button>停止</button>
    <script>
        // 获取开始按钮
        var start_btn = $('button')[0];
        // 获取开始按钮
        var stop_btn = $('button')[1];
        // 获取box盒子
        var aBox = $(".box")[0];
        // 初始化定时器
        var timer = null;
        var moveTop = 0;
        var moveLeft = 0;
        var flag = true;

        timer = setInterval(move, 50);
        start_btn.onclick = function () {

            clearInterval(timer);
            timer = setInterval(move, 50);
            flag = false;


        }

        stop_btn.onclick = function () {
            clearInterval(timer);
        }
        function move() {

            if (moveLeft < 380 && moveTop == 0) {
                moveLeft += 10;
                aBox.style.left = moveLeft + 'px';
                console.log(aBox.offsetLeft);
            } else if (moveLeft == 380 && moveTop < 380) {
                moveTop += 10;
                aBox.style.top = moveTop + 'px';
                console.log(aBox.offsetTop);
            }
            else if (moveTop == 380 && moveLeft > 0) {
                moveLeft -= 10;
                aBox.style.left = moveLeft + 'px';
                console.log(aBox.offsetLeft);
            }
            // ( moveLeft==0 && moveTop>0) 
            else {
                moveTop -= 10;
                aBox.style.top = moveTop + 'px';
                console.log(aBox.offsetTop);
            }

        }
        function $(select) {
            return document.querySelectorAll(select);
        }
    </script>
</body>

</html>